<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: LoginController.php
// +----------------------------------------------------------------------
// | Author: liuju
// +----------------------------------------------------------------------
// | Description: 主要实现用户登录、信息获取、信息修改功能
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2018-12-27 Author: liuju Modification: 创建
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Frontend\V10\Auth;


use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\V10\Auth\BindingUserPassRequest;
use App\Http\Requests\Frontend\V10\Auth\BindUserPhoneRequest;
use App\Http\Requests\Frontend\V10\Auth\LoginRequest;
use App\Http\Requests\Frontend\V10\Auth\WechatLoginReqeust;
use App\Models\User;
use App\Models\UserGlobal;
use App\Models\UserLoginLog;
use App\Models\UserWechat;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Facades\JWTAuth;

class LoginController extends Controller
{
    use AuthenticatesUsers;


    /**
     * LoginController constructor.
     */
    public function __construct()
    {
        $this->middleware('auth:api')->only(['logout']);
    }


    /**
     * Description: 用户登录：验证用户身份信息，实现单点登录
     * Author: liuju
     * DateTime: 2018-12-27 11:39
     * @param LoginRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(LoginRequest $request)
    {
        if(!$getUser = User::where(['phone_num'=>$request->get('phone_num')])->first()){
            return failed('该用户不存在');
        }
        $token = auth('api')->attempt($request->only(['phone_num', 'password']));
        if (!$token) {
            //由于加密方式不同，需要开辟其他方式验证旧数据密码
           if(hash_equals($getUser->password,hash('sha512',$request->get('password')))){
               $token = JWTAuth::fromUser($getUser);
           }else{
               return respond([], '账号或密码错误', Response::HTTP_BAD_REQUEST);
           }
        }

        //覆盖Redis中该用户已有的token，使同用户其他设备登录状态失效
        $user = $getUser;
        User::updateTokenRecord($user,$token);
        UserLoginLog::createLog($user,UserLoginLog::TYPE_PHONE);
        UserGlobal::jpushDataUpdate($user, $request); //极光相关更新
        return respond([
            'user'=>User::getCurrentUserDetailByApp($user),
            'token'=>$token,
        ], '登录成功', Response::HTTP_OK);
    }


    /**
     * Description:用户微信登录
     * Author: liuju
     * DateTime: 2018-12-29 14:03
     * @param WechatLoginReqeust $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function wechatLogin(WechatLoginReqeust $request)
    {
        $openid = $request->get('openid');
        $wechatUser = UserWechat::where('openid', $openid)->first();
        if (!$wechatUser) {
            return respond([], '该用户尚未关联微信', Response::HTTP_NOT_FOUND);
        }
        $user = $wechatUser->user;
        if (empty($user)) {
            return respond([], '数据未知错误', Response::HTTP_EXPECTATION_FAILED);
        }
        return respond([], '登录成功', Response::HTTP_OK, ['token' => auth('api')->tokenById($user->id)]);
    }


    /**
     * Description: 微信绑定已有用户，验证用户手机号准确性
     * Author: liuju
     * DateTime: 2018-12-29 10:55
     * @param BindUserPhoneRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindingPhone(BindUserPhoneRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        $user = User::where('phone_num', $phoneNum)->first();
        if (empty($user)) {
            return respond([], '该号码用户不存在');
        }
        $key = 'phone:binding:' . $user->phone_num;
        if (Cache::get($key)) {
            return respond([], '您已验证过手机号码，请勿重复此操作', Response::HTTP_OK, ['next_uri' => 'bindPass']);
        }
        $openid = $request->get('openid');
        $userWechat = $user->wechat;
        if (!empty($userWechat) && $userWechat->openid && $userWechat->openid != $openid) {
            return respond([], '该用户已绑定微信');
        }
        if (!empty($userWechat) && $userWechat->openid == $openid) {
            return respond([], '您已绑定此用户请勿重复操作');
        }
        if (empty($userWechat)) {
            Cache::add($key, time(), 30);
            return respond([], '验证成功', Response::HTTP_OK, ['next_uri' => 'bindPass']);
        }
        return respond([], '未知错误');
    }


    /**
     * Description:绑定用户：验证用户密码操作
     * Author: liuju
     * DateTime: 2018-12-29 11:29
     * @param BindingUserPassRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function bindingPass(BindingUserPassRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        $user = User::where('phone_num', $phoneNum)->first();
        if (empty($user)) {
            return respond([], '该号码用户不存在');
        }
        $key = 'phone:binding:' . $user->phone_num;
        if (!Cache::get($key)) {
            return respond([], '请求有误，您尚未验证手机号');
        }
        $openid = $request->get('openid');
        $userWechat = $user->wechat;
        if (!empty($userWechat) && $userWechat->openid && $userWechat->openid != $openid) {
            return respond([], '该用户已绑定微信');
        }
        if (!empty($userWechat) && $userWechat->openid == $openid) {
            return respond([], '您已绑定此用户请勿重复操作');
        }
        if (empty($userWechat)) {
            $userWechat = new UserWechat();
            $userWechat->user_id = $user->id;
            $userWechat->openid = $openid;
            if (!$userWechat->save()) {
                return respond([], '数据内部未知错误');
            }
            Cache::forget($key);
            return success([], ['token' => auth('api')->tokenById($user->id)]);
        }
        return respond([], '未知错误');
    }


    /**
     * Description: 用户注销登录
     * Author: liuju
     * DateTime: 2018-12-27 17:00
     * @return \Illuminate\Http\JsonResponse
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function logout()
    {
        JWTAuth::parseToken()->invalidate();
        return success([], [], '注销登录成功');
    }

}